#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
搜索相关API
"""

from flask_restful import Resource, reqparse
from app.services.civil_code_service import civil_code_service
from app.utils.response_utils import create_response
from flask import request, current_app

class SearchAPI(Resource):
    """搜索API"""
    
    def get(self):
        """搜索条文"""
        try:
            # 解析查询参数
            parser = reqparse.RequestParser()
            parser.add_argument('q', type=str, required=True, help='搜索关键词不能为空', location='args')
            parser.add_argument('page', type=int, default=1, help='页码', location='args')
            parser.add_argument('per_page', type=int, default=20, help='每页条数', location='args')
            
            args = parser.parse_args()
            
            # 执行智能搜索
            result = civil_code_service.smart_search(
                query=args['q'].strip(),
                page=args['page'],
                per_page=min(args['per_page'], 50)  # 限制最大每页条数
            )
            
            return create_response(
                success=True,
                data=result,
                message=f"搜索'{args['q']}'完成"
            )
            
        except Exception as e:
            current_app.logger.error(f"搜索失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'SEARCH_ERROR',
                    'message': '搜索失败',
                    'details': str(e) if current_app.debug else '搜索服务异常'
                },
                status_code=500
            )

class SearchSuggestionsAPI(Resource):
    """搜索建议API"""
    
    def get(self):
        """获取搜索建议"""
        try:
            # 解析查询参数
            parser = reqparse.RequestParser()
            parser.add_argument('q', type=str, required=True, help='搜索关键词不能为空', location='args')
            parser.add_argument('limit', type=int, default=10, help='建议数量', location='args')
            
            args = parser.parse_args()
            
            # 获取搜索建议
            suggestions = civil_code_service.get_search_suggestions(
                query=args['q'].strip(),
                limit=min(args['limit'], 20)  # 限制最大建议数量
            )
            
            return create_response(
                success=True,
                data={'suggestions': suggestions},
                message=f"获取'{args['q']}'的搜索建议成功"
            )
            
        except Exception as e:
            current_app.logger.error(f"获取搜索建议失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'SUGGESTIONS_ERROR',
                    'message': '获取搜索建议失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )
